import {ElementRef, HostListener, Directive} from '@angular/core'

@Directive({
    selector: 'span[datedisplay]'
})

export class DateDisplay {

    @HostListener('load',['$event.target'])
    onListened(span: HTMLTextAreaElement): void {
        console.log("DateDisplay load");
        this.adjust();
    }

    constructor(public element: ElementRef){
        // console.log("DateDisplay constructor");
    }

    ngOnInit(): void {
        // console.log("DateDisplay ngOnInit");
    }

    ngAfterContentInit(): void {
        // console.log("DateDisplay ngAfterContentInit");
    }

    ngAfterViewInit(): void {
        // console.log("DateDisplay ngAfterViewInit");
        this.adjust();
    }

    adjust(): void {
        let attr_datestr = this.element.nativeElement.attributes.getNamedItem("datestr")
        if(!attr_datestr) {
            return;
        }
        let date_str = attr_datestr.value;
        let update_date:Date = new Date(Date.parse(date_str.replace(/-/g, "/")));
        let now:Date = new Date();
        
        let new_time = "";

        if(update_date.toDateString() == now.toDateString()) {
            new_time = update_date.getHours() + ":" + update_date.getMinutes();
        } else {
            let month = update_date.getMonth() + 1;
            let day = update_date.getDate();
            new_time = month + "月" + day + "日";
        }

        this.element.nativeElement.innerHTML = new_time;
        // console.log(this.element);
    }
}